﻿
window.Foresight = window.Foresight || {};
(function (ns) {
    ns.Util = {};
    ns.Util.JsonResponseCode = {
        UNAUTHORIZED: -100,
        SUCCEED: 0
    };
    ns.Util.AppId = 'A6940277064674';
    ns.Util.AppKey = '796C6322-511E-3E1F-4115-84F2D0A174A2';
    ns.Util.GetSHA1APPKey = function () {
        var now = Date.now();
        var ss = ns.Util.AppId + "UZ" + ns.Util.AppKey + "UZ" + now;
        var appKey = SHA1(ss) + "." + now;
        return appKey;
    }
    ns.Util.getQueryString = function (key, url) {
        var vars = [],
            hash;
        var pageurl = url || window.location.href;
        var hashes = pageurl.slice(pageurl.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = window.decodeURIComponent(hash[1]);
        }
        return !!key ? vars[key] : vars;
    };
    ns.Util.getQueryURL = function (url) {
        var vars = [],
            hash;
        var pageurl = url || window.location.href;
        var hashes = pageurl.split('?');
        if (hashes.length > 1) {
            return hashes[0];
        }
        return pageurl;
    };
    ns.Util.api_ajax = function (options) {
        var post_form = options.data;
        post_form.phonetype = api.systemType;
        post_form.appVersion = api.appVersion;
        var opt = null;
        if (/post/ig.test(options.type)) {
            opt = {
                url: options.url,
                method: options.type,
                cache: false,
                dataType: 'json',
                timeout: 300,
                data: {
                    values: post_form,
                    files: options.files || {}
                }
            };
            if (options.hasheader) {
                opt.headers = {
                    'X-APICloud-AppId': ns.Util.AppId,
                    'X-APICloud-AppKey': ns.Util.GetSHA1APPKey(),
                    'Access-Control-Allow-Origin': '*'
                };
            }
        } else {
            var arr = [];
            var url = options.url;
            for (var key in post_form) {
                arr.push(key + '=' + encodeURIComponent(post_form[key]));
            }
            if (arr.length) {
                if (!/\?/.test(url)) {
                    url = options.url + '?' + arr.join('&');
                } else {
                    if (/[\?\&]$/.test(url)) {
                        url = options.url + arr.join('&');
                    } else {
                        url = options.url + '&' + arr.join('&');
                    }
                }
            }
            opt = {
                url: url,
                method: options.type || 'get',
                cache: false,
                dataType: 'json',
                timeout: 300
            };
        }
        var toast = null;
        if (options.toast) {
            toast = new auiToast();
            options.toastmsg = options.toastmsg || '加载中';
            toast.loading({
                title: options.toastmsg,
                duration: 2000
            }, function (ret) { });
        }
        api.ajax(opt, function (ret, err) {
            if (options.toast) {
                toast.hide();
            }
            if (ret) {
                data = ret;
                if (options.hasheader) {
                    options.success.call(this, data, null);
                    return;
                }
                if (data == undefined || data == null) {
                    throw new Error("Ajax response null.");
                } else if (typeof data.Code == "undefined") {
                    throw new Error("Incorrect json data.");
                }
                if (data.Code == ns.Util.JsonResponseCode.UNAUTHORIZED) {
                    ns.Util.removeAPIUrl();
                    ns.Util.removeUid(true);
                } else if (data.Code == ns.Util.JsonResponseCode.SUCCEED) {
                    if (typeof options.success == "function")
                        options.success.call(this, data.Result, null); //调用指定的成功处理函数
                } else if (data.Code < 0) {
                    if (typeof options.error == 'function')
                        options.error.call(this, data.Error, null); //调用指定的错误处理函数
                } else {
                    throw new Error("Unknown json code: " + data.Code + ".");
                }
            } else {
                if (err.code == 0) {
                    if (api.toast) {
                        api.toast({
                            msg: '当前服务不可用，请稍后再试',
                            duration: 5000,
                            location: 'bottom'
                        });
                    }
                } else if (err.code == 1) {
                    if (api.toast) {
                        api.toast({
                            msg: '连接服务器超时',
                            duration: 5000,
                            location: 'bottom'
                        });
                    }
                } else if (err.code == 2) {
                    if (api.toast) {
                        api.toast({
                            msg: '授权错误',
                            duration: 2000,
                            location: 'bottom'
                        });
                    }
                } else if (err.code == 3) {
                    if (api.toast) {
                        api.toast({
                            msg: '数据类型错误',
                            duration: 2000,
                            location: 'bottom'
                        });
                    }
                }
                if (typeof options.error == 'function') {
                    options.error.call(this, '', null);
                }
            }
        });
    }
    ns.Util.ajax = function (options) {
        //获取apiurl
        var device_id = api.getPrefs({
            sync: true,
            key: 'jpush_device_id'
        });
        options.data = ns.Util.extend(options.data, {
            device_id: device_id,
            device_type: api.systemType
        });
        var uid = api.getPrefs({
            sync: true,
            key: 'uid'
        });
        if (!uid && !options.ignoreuid) {
            ns.Util.open_login();
            return;
        }
        options.data = ns.Util.extend(options.data, {
            uid: uid,
            IsAPPUser: 1
        });
        if (!options.url) {
            options.url = CONFIG.apiurl;
            if (!options.is_getapi) {
                var apiOption = ns.Util.getAPIUrl();
                if (apiOption) {
                    options.url = apiOption.apiUrl;
                }
            }
        }
        ns.Util.api_ajax(options);
    };
    ns.Util.extend = function (o, n) {
        for (var p in n) {
            if (n.hasOwnProperty(p) && (!o.hasOwnProperty(p)))
                o[p] = n[p];
        }
        return o;
    };
    ns.Util.post = function (data, callback, options) {
        if (!options) {
            options = {};
        }
        return ns.Util.ajax(ns.Util.extend(options, {
            cache: false,
            success: function (result, textStatus) {
                if (typeof callback == "function") callback(true, result, null);
            },
            error: function (err, textStatus) {
                if (typeof callback == "function") callback(false, null, err);
            },
            url: (options && options.url) || '',
            data: data,
            type: 'POST'
        }));
    };
    //callback: funtion(succeed,data,error){};
    ns.Util.get = function (data, callback, options) {
        if (!options) {
            options = {};
        }
        return ns.Util.ajax(ns.Util.extend(options, {
            cache: false,
            success: function (result, textStatus) {
                if (typeof callback == "function") callback(true, result, null);
            },
            error: function (err, textStatus) {
                if (typeof callback == "function") callback(false, null, err);
            },
            url: (options && options.url) || '',
            data: data,
            type: 'GET'
        }));
    };
    ns.Util.open_login = function (options) {
        api.sendEvent({
            name: 'onlogout'
        });
    }
    ns.Util.openWin = function (name, title, pageParam, options) {
        var type = ns.Util.getQueryString('type', name);
        var mail = ns.Util.getQueryString('mail', name);
        name = ns.Util.getQueryURL(name);
        if (!pageParam || pageParam == null) {
            pageParam = {
                title: title,
                url: name + '.html'
            };
        }
        if (type) {
            pageParam.type = type;
        }
        if (mail) {
            pageParam.mail = mail;
        }
        if (!pageParam.title) {
            pageParam.title = title;
        }
        if (!pageParam.url) {
            pageParam.url = name + '.html'
        }
        var delay = 100;
        if (api.systemType != 'ios') {
            delay = 100;
        }
        var url = '../frame.html';
        if (options && options.ismain) {
            url = 'frame.html';
        }
        if (options && options.needlogin) {
            var ismain = (options && options.ismain) || false;
            ns.Util.post({
                action: 'checkloginstatus'
            }, function (succeed, data, err) {
                options.needlogin = false;
                if (succeed) {
                    ns.Util.openWin(name, title, pageParam, options);
                } else if (err) {
                    ns.Util.open_login(options);
                }
            }, {
                ismain: ismain
            });
            return;
        }
        api.openTabLayout({
            hideNavigationBar: true,
            hideTabBar: true,
            useWKWebView: true,
            name: name,
            url: url,
            delay: delay,
            slidBackEnabled: false,
            vScrollBarEnabled: false,
            pageParam: pageParam,
            allowEdit:true,
            rect: {
                x: 0,
                y: 0,
                w: 'auto',
                h: 'auto'
            }
        });
    }
    ns.Util.openFrame = function (name, pageParam, options) {
        var url = '../html/' + name + '.html';
        if (options && options.ismain) {
            url = './html/' + name + '.html';
        }
        if (options && options.url) {
            url = options.url;
        }
        var frameOption = {
            useWKWebView: true,
            name: name,
            url: url,
            bounces: false,
            allowEdit:true,
        };
        if (pageParam) {
            frameOption.pageParam = pageParam;
        }
        if (options && options.rect) {
            frameOption.rect = options.rect;
        }
        api.openFrame(frameOption);
    }
    ns.Util.toast = function (msg) {
        api.toast({
            msg: msg,
            duration: 2000,
            location: 'bottom'
        });
    }
    ns.Util.getAPIUrl = function () {
        if (!CONFIG.isSingleSite) {
            var apiUrl = api.getPrefs({
                sync: true,
                key: 'apiUrl'
            });
            var companyName = api.getPrefs({
                sync: true,
                key: 'companyName'
            });
            if (apiUrl && companyName) {
                return {
                    apiUrl: apiUrl,
                    companyName: companyName
                }
            }
        }
        return null;
    }
    ns.Util.setAPIUrl = function (apiUrl, companyName) {
        if (CONFIG.isSingleSite) {
            return;
        }
        api.setPrefs({
            key: 'apiUrl',
            value: apiUrl
        });
        api.setPrefs({
            key: 'companyName',
            value: companyName
        });
    }
    ns.Util.removeAPIUrl = function () {
        if (CONFIG.isSingleSite) {
            return;
        }
        api.removePrefs({
            key: 'apiUrl'
        });
        api.removePrefs({
            key: 'companyName'
        });
    }
    ns.Util.removeUid = function (logout) {
        api.removePrefs({
            key: 'uid'
        });
        api.removePrefs({
            key: 'loginname'
        });
        api.removePrefs({
            key: 'username'
        });
        api.removePrefs({
            key: 'headimg'
        });
        api.removePrefs({
            key: 'phonenumber'
        });
        api.removePrefs({
            key: 'positionname'
        });
        if (logout) {
            api.sendEvent({
                name: 'onlogout'
            });
        }
    }
    ns.Util.confirmPer = function (perm, callback) {
        var has = ns.Util.hasPermission(perm);
        var granted = true;
        if (has && has.length > 0) {
            for (var i = 0; i < has.length; i++) {
                if (!has[i].granted) {
                    granted = false;
                }
            }
        }
        if (!granted) {
            api.confirm({
                title: '提醒',
                msg: '没有获得 ' + perm + " 权限\n是否前往设置？",
                buttons: ['去设置', '取消']
            }, function (ret, err) {
                if (1 == ret.buttonIndex) {
                    ns.Util.reqPermission(perm, callback);
                }
            });
            return false;
        }
        if (callback) {
            callback();
        }
        return true;
    };
    ns.Util.hasPermission = function (one_per) {
        if (!one_per) {
            return;
        }
        var perms = new Array();
        perms.push(one_per);
        perms.push('storage');
        var rets = api.hasPermission({
            list: perms
        });
        return rets;
    };
    ns.Util.reqPermission = function (one_per, callback) {
        var perms = new Array();
        perms.push(one_per);
        perms.push('storage');
        api.requestPermission({
            list: perms,
            code: 100001
        }, function (ret, err) {
            if (callback) {
                var list = ret.list;
                if (list && list.length > 0) {
                    var granted = true;
                    for (var i = 0; i < list.length; i++) {
                        if (!list[i].granted) {
                            granted = false;
                        }
                    }
                    if (granted) {
                        callback();
                    }
                }
                return;
            }
            var str = '请求结果：\n';
            str += '请求码: ' + ret.code + '\n';
            str += "是否勾选\"不再询问\"按钮: " + (ret.never ? '是' : '否') + '\n';
            str += '请求结果: \n';
            var list = ret.list;
            for (var i in list) {
                str += list[i].name + '=' + list[i].granted + '\n';
            }
        });
    };
    ns.Util.init_search = function () {
        var searchBar = document.querySelector(".aui-searchbar");
        var searchBarInput = document.querySelector(".aui-searchbar input");
        var searchBarBtn = document.querySelector(".aui-searchbar .aui-searchbar-btn");
        var searchBarClearBtn = document.querySelector(".aui-searchbar .aui-searchbar-clear-btn");
        searchBarInput.onclick = function () {
            searchBarBtn.style.display = 'block';
            searchBarBtn.style.marginRight = 0;
            searchBarBtn.textContent = "搜索";
            searchBarBtn.classList.add("aui-text-info");
            if (searchBarInput.value == '') {
                searchBarClearBtn.style.display = 'none';
                searchBarBtn.style.display = 'none';
            } else {
                searchBarClearBtn.style.display = 'block';
                searchBarBtn.style.display = 'block';
            }
        }
        searchBarInput.oninput = function () {
            if (searchBarInput.value == '') {
                searchBarClearBtn.style.display = 'none';
                searchBarBtn.style.display = 'none';
            } else {
                searchBarClearBtn.style.display = 'block';
                searchBarBtn.style.display = 'block';
            }
        }
        searchBarClearBtn.onclick = function () {
            searchBarBtn.style.display = 'none';
            this.style.display = 'none';
            app.form.keywords = '';
            searchBarBtn.classList.remove("aui-text-info");
            searchBarBtn.textContent = "";
            if (typeof (app.searchbar_click) != 'undefined') {
                app.searchbar_click = false;
            }
            app.get_data();
        }
        searchBarBtn.onclick = function () {
            app.do_search();
        }
        searchBarInput.onkeypress = function (e) {
            var keycode = e.keyCode;
            if (keycode == '13') {
                e.preventDefault();
                searchBarInput.blur();
                app.do_search();
            }
        }
    }
    //添加水印Base64
    ns.Util.setWatermark = function (imagePath, waterTypeName, imageTime, GPSLocation) {
        var username = api.getPrefs({ sync: true, key: 'username' });
        var canvas = document.createElement("canvas");
        var context = canvas.getContext("2d");
        return new Promise((resolve, reject) => {
            var img = new Image();
            img.crossOrigin = "Anonymous";// 注意这个属性一定要在src之前, 否则ios无法成功转base64
            img.src = imagePath;
            img.onload = function () {
                var scalewidth = 1;
                var sizewidth = document.documentElement.clientWidth; // 可以根据具体的要求去设定
                if (img.width > sizewidth) {
                    scalewidth = sizewidth / img.width;
                }
                context.width = sizewidth;
                context.height = img.height * scalewidth; // 计算等比缩小后图片

                //核心代码，缺一不可
                var ratio = window.devicePixelRatio || 1;
                // canvas 大小
                canvas.width = context.width * ratio;
                canvas.height = context.height * ratio;
                canvas.style.width = context.width + 'px';
                canvas.style.height = context.height + 'px';

                //计算水印宽度
                let fontSize = 14 * ratio;//一个字的宽度
                context.font = fontSize + "px 楷体";
                var cavasWidth = context.measureText('时    间：' + imageTime).width;

                //计算1排最多好多个字,减去6个字的宽度
                var wordnumber = Math.floor(canvas.width / fontSize) - 7;//一排最多几个字
                var GPSWidthRatio = 0;
                if (GPSLocation != undefined && GPSLocation != '' && GPSLocation != "undefined") {
                    cavasWidth = context.measureText('地    点：' + GPSLocation).width;
                    //当定位信息长度大于当前手机宽度时，需要处理高度
                    if (GPSLocation.length > wordnumber) {
                        GPSWidthRatio = parseInt(GPSLocation.length / wordnumber);
                    }
                }
                if (GPSLocation == undefined || GPSLocation == "" || GPSLocation == "undefined") {
                    GPSLocation = "--";
                }
                cavasWidth = cavasWidth + 20 * ratio;//水印宽度
                if (GPSWidthRatio > 0) {
                    cavasWidth = context.width * ratio - 20 * ratio;
                }
                var heightRatio = context.height * ratio;//画布高

                context.drawImage(img, 0, 0, context.width * ratio, heightRatio); //// 将image放到目标canvas指定位置，指定宽高渲染
                context.lineWidth = 1;////lineWidth默认值为1
                //添加蓝色色背景
                context.fillStyle = "#1192f9";
                context.fillRect(10 * ratio, heightRatio - 109 * ratio - GPSWidthRatio * fontSize, cavasWidth, 32 * ratio);
                //添加水印类型
                let fontSizeTitle = 18 * ratio;
                context.font = fontSizeTitle + "px 楷体";
                context.fillStyle = "#fff";
                context.textAlign = "center";
                context.fillText(waterTypeName, cavasWidth / 2 + 20, heightRatio - 87 * ratio - GPSWidthRatio * fontSize);
                //添加阴影
                context.fillStyle = "rgba(0,0,0,0.3)";
                context.fillRect(10 * ratio, heightRatio - 77 * ratio - GPSWidthRatio * fontSize, cavasWidth, 70 * ratio + GPSWidthRatio * fontSize + 5);
                //添加时间 地点
                context.font = fontSize + "px 楷体";
                context.fillStyle = "#fff";
                context.textAlign = "left";
                context.fillText('时    间：' + imageTime, 20 * ratio, heightRatio - 60 * ratio - GPSWidthRatio * fontSize);
                context.fillText('巡检人：' + username, 20 * ratio, heightRatio - 40 * ratio - GPSWidthRatio * fontSize);

                //判断定位地址是否大于手机宽度
                if (GPSWidthRatio > 0) {
                    for (let i = 0; i < GPSWidthRatio + 1; i++) {
                        var lenword = GPSLocation.slice(i * wordnumber, wordnumber * (i + 1));
                        if (i == 0) {
                            context.fillText('地    点：' + lenword, 20 * ratio, heightRatio - 20 * ratio - GPSWidthRatio * fontSize);
                        }
                        else {
                            context.fillText(lenword, 20 * ratio + 4 * fontSize - 10, heightRatio - 20 * ratio - fontSize * (GPSWidthRatio - i) + 10 * i);
                        }
                    }
                }
                else {
                    context.fillText('地    点：' + GPSLocation, 20 * ratio, heightRatio - 20 * ratio + GPSWidthRatio * fontSize);
                }

                var dataURL = canvas.toDataURL("image/png");
                // var baseStr = dataURL.split(',').pop();  // 取base64图片值   
                var baseStr = dataURL.replace('data:image/png;base64,', ''); // 取base64图片值   
                resolve(baseStr);
            };
        })
    }
    //时间处理(安卓、ios同时兼容)
    ns.Util.SetTime_style = function (time) {
        if (time.indexOf('T') > 0) {
            time = time.substring(0, 19).replace("T", " ");
        }
        var dt = new Date(time.replace(/-/g, "/"));
        var Y = dt.getFullYear();
        var M = dt.getMonth() + 1 < 10 ? '0' + (dt.getMonth() + 1) : dt.getMonth() + 1;
        var D = dt.getDate() < 10 ? '0' + dt.getDate() : dt.getDate();
        var H = dt.getHours();
        var S = dt.getMinutes();
        H = H < 10 ? '0' + H : H;
        S = S < 10 ? '0' + S : S;

        var nowDate = new Date();
        var nowY = nowDate.getFullYear();
        var nowM = nowDate.getMonth() + 1;
        var nowD = nowDate.getDate();
        var nowH = nowDate.getHours();

        if (Y == nowY) {
            if (M == nowM) {
                if (D == nowD) {
                    if (H < 12) {
                        return '上午 ' + H + ':' + S;
                    } else {
                        return '下午 ' + H + ':' + S;
                    }
                }
                else if (D == nowD - 1) {
                    return '昨天 ' + H + ':' + S;
                }
                else {
                    return M + '/' + D + ' ' + H + ':' + S;
                }
            } else {
                return M + '/' + D + ' ' + H + ':' + S;
            }
        }
        else {
            // return Y + '/' + M + '/' + D + ' ' + H + ':' + S;
            return Y + '/' + M + '/' + D;
        }

    }
    //时间处理 yyyy-mm-dd hh:ss
    ns.Util.DealTimeYYMMDDHHSS = function (time) {
        var lsDate = new Date(time);
        var Y = lsDate.getFullYear();
        var M = lsDate.getMonth() + 1 < 10 ? '0' + (lsDate.getMonth() + 1) : lsDate.getMonth() + 1;
        var D = lsDate.getDate() < 10 ? '0' + lsDate.getDate() : lsDate.getDate();
        var H = lsDate.getHours() < 10 ? '0' + lsDate.getHours() : lsDate.getHours();
        var S = lsDate.getMinutes() < 10 ? '0' + lsDate.getMinutes() : lsDate.getMinutes();

        return Y + '-' + M + '-' + D + ' ' + H + ':' + S;
    }
    ns.Util.DateFormatYY = function (time) {
        if (time.indexOf('T') > 0) {
            time = time.substring(0, 19).replace("T", " ");
        }
        var dt = new Date(time.replace(/-/g, "/"));
        var H = dt.getHours();
        var S = dt.getMinutes();
        H = H < 10 ? '0' + H : H;
        S = S < 10 ? '0' + S : S;
        return H+':'+S;
    }
    ns.Util.DateFormatChinese = function (time, type) {
        if (time.indexOf('T') > 0) {
            time = time.substring(0, 19).replace("T", " ");
        }
        var dt = new Date(time.replace(/-/g, "/"));
        var Y = dt.getFullYear();
        var M = dt.getMonth() + 1 < 10 ? '0' + (dt.getMonth() + 1) : dt.getMonth() + 1;
        var D = dt.getDate() < 10 ? '0' + dt.getDate() : dt.getDate();
        if (type == 1) {
            return Y + '年' + M + '月';
        }
        return Y + '年' + M + '月' + D + '日';
    }
    ns.Util.DealLocationDescribe = function (val) {
        var result = '';
        if (val == undefined || val == '' || val.length < 4) {
            return result;
        }
        var len1 = val.substr(0, 1);
        var len2 = val.substr(val.length - 2, val.length);
        var len3 = val.substr(1, val.length - 3);
        if (len1 == '在' && len2 == '附近') {
            return len3;
        }
        return val;
    },
    ns.Util.init_pull = function (exscrool, IsUpLoad) {
        var pullRefresh = new auiPullToRefresh({
            container: document.querySelector('.aui-refresh-content'),
            triggerDistance: 100
        }, function (ret) {
            if (ret.status == "success") {
                setTimeout(function () {
                    app.form.pageindex = 0;
                    
                    if (IsUpLoad) {
                        app.scroll_top = ret.scrollTop + 1;
                        app.form.pageindex = app.current_item_length;
                        app.get_data();
                    }
                    else {
                        app.get_data();
                    }pullRefresh.cancelLoading(); //刷新成功后调用此方法隐藏
                }, 1500)
            }
        })
        if ((typeof (exscrool) != 'undefined' && exscrool == true) || IsUpLoad) {
            return;
        }
        if (IsUpLoad) {
            var scroll = new auiScroll({
                listen: true,
                distance: 5 //判断到达底部的距离，isToBottom为true
            }, function (ret) {
                if (ret.isToBottom) {
                    app.form.pageindex = 0;
                    app.get_data();
                }
            });
        }
        else {
            var scroll = new auiScroll({
                listen: true,
                distance: 5 //判断到达底部的距离，isToBottom为true
            }, function (ret) {
                if (ret.isToBottom && app.can_scroll) {
                    if (app.scroll_top > ret.scrollTop) {
                        app.scroll_top = ret.scrollTop;
                        return;
                    }
                    app.scroll_top = ret.scrollTop + 1;
                    app.form.pageindex = app.current_item_length;
                    app.get_data();
                }
            });
        }

    }
})(window.Foresight);
